#!/usr/bin/env python

from docker import Client
import threading, time


# Collecting Docker container's running metric
class MetricsCollector(threading.Thread):
    def __init__(self, docker_clint, container_name):
        threading.Thread.__init__(self)
        self.container_name = container_name
        self.metrics_generator = docker_client.stats(container_name, decode=True)
        self.metrics = []

        self.setDaemon(True)

    def run(self):
        for m in self.metrics_generator:
            self.metrics.append(m)

    def analyze(self):
        print self.metrics[-1]["cpu_stats"]["system_cpu_usage"]


# Set up docker client
docker_client = Client(base_url='unix://var/run/docker.sock')
# Connect to all Docker Containers and start monitoring
containers = {}
for c in docker_client.containers():     
    container_name = c["Names"][0][1:]
    containers[container_name] = MetricsCollector(docker_client, container_name)
    containers[container_name].start()

target_container_name = 'cadvisor'
while True:
    time.sleep(1)
    containers[target_container_name].analyze()
